Ext.ns('cn.hls.web.action.biz.car');
var listView = cn.hls.web.action.biz.car.listView;
var url = cfg.cxt + "/carAttach/info.action?id=";
listView = function() {
	var store, grid, win,attachWin,attachPanel, iframe;
	var sm = new Ext.grid.CheckboxSelectionModel({
		singleSelect : false  //单选设置为false　表示允许多选
	});
	var fields = [ "id",// 编号
	"licenseNum",//车牌号
	"type",//车辆类型
	"fileName",//附件名称
	"filePath",//附件路径
	"createTime"//创建时间
	];
	return {
		init : function() {
			  //------------------------------------------------- store
            store = this.createStore();
            //查询条件
			store.on('beforeload', function() {
				if(queryRole){
					this.baseParams = {
						//"licenseNum" : Ext.getCmp('txt_licenseNum').getValue(),
						"licenseNum":licenseNum==''?undefined:licenseNum,
						//"type" : Ext.getCmp('cmb_type').getValue(),
						"fileName" : Ext.getCmp('txt_fileName').getValue()
					};
				}
			});
            
			//------------------------------------------------- grid
			grid = this.createGrid();
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					listView.editInit();
				});
			}
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			                if(cellIndex>1){
				                var cell = view.getCell(rowIndex, cellIndex);  
		                        tip.body.dom.innerHTML = cell.innerHTML;  
			                }else{
			                	return false;
			                }
			            }  
			        }  
			    });  
			}); 
			
			// ------------------------------------------------- viewport
			new Ext.Viewport({ 
			      layout : 'fit',
				  items : [grid]
			});
			this.queryResItem();
		},		/**获取查询参数**/
		createStore : function() {
			return new ExtStore({
				url : '/carAttach/list.action',
				fields : fields
			});
		},
	
		createGrid : function() {
			return new ExtGrid({
				store : store,
				title : '<div class="panelTitleCss">车辆附件信息列表</div>',
				sm : sm,
				columnLines : true,
				columns : listView.createColumns(),
				tbar : listView.createQueryTbar(),
				bbar : {
					id : 'page',
					xtype : 'pageinfobar',
					pageSize : 20,
					store : store,
					pageMethod : listView.queryResItem
				}
			});
		},
		createColumns : function() {
			var cols = [
					new Ext.grid.RowNumberer(),
					sm,
					{
						sortable : true,dataIndex : 'licenseNum',width : 60,autoWidth :true,header : '车牌号',align : 'center'
					},{
						sortable : true,dataIndex : 'type',width : 60,autoWidth :true,header : '类型',align : 'center',
						renderer:function(val){
							if(val==1){
								return '主车';
							}else if(val==2){
								return '挂车';
							}else{
								return '';
							}
						}
					},{
						sortable : true,dataIndex : 'fileName',width : 60,autoWidth :true,header : '附件名称',align : 'center'
					},{
						sortable : true,dataIndex : "createTime",header : '创建时间',autoWidth : true,align : 'center',width : 75,
						renderer : function(val) {
							if(val!=null){
								return new Date(val).dateFormat('Y-m-d');
							}else{
								return '';
							}
						}
					},{
						sortable : true,dataIndex : 'filePath',width : 150,autoWidth :true,header : '附件路径',align : 'center'
						,renderer:function(val){
							if(val!=null){
								var a=val.split(',');
								var result='';
								for(var i=0;i<a.length;i++){
									result+='<a href="javascript:void(0);" style="text-decoration:none;" onclick="listView.attachView(\''+a[i]+'\');">【附件'+(i+1)+'】</a>';
								}
								return result;
							}else{
								return '';
							}
						}
					}
			];
			return cols;
		},
		createQueryTbar : function() {
			if (queryRole) {// 查询权限
				tbarOpr.push('->');
			 
				/*tbarOpr.push({
					xtype : "textfield",
					width : 90,
					id : 'txt_licenseNum',
					emptyText : '请输入车牌号',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push({xtype : "label",text : "车辆类型",style : 'margin-left:8px;'});  
				tbarOpr.push(  new Ext.form.ComboBox({
					id : 'cmb_type',
					xtype : 'combo',
					style : 'margin-left:8px;',
					name : 'car_licenseColor',
					store : new Ext.data.SimpleStore({
						fields : [ 'value', 'text' ],
						data : [ [ '', '全选 ' ], [ 1, '主车 ' ],
								[ 2, '挂车' ] ]
					}),
					emptyText : '请选择',
					mode : 'local',
					triggerAction : 'all',
					valueField : 'value',
					displayField : 'text',
					width : 60,
					value : '',
					forceSelection : true,
					editable : false,
					typeAhead : true
				}));
				tbarOpr.push('-'); */
				
				tbarOpr.push({
					xtype : "textfield",
					width : 120,
					id : 'txt_fileName',
					emptyText : '请输入附件名称',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push('-');
				
				tbarOpr.push({
					text : '查询',
					iconCls : 'mainContent',
					handler : function() {
						listView.queryResItem();
					}
				});

				tbarOpr.push({
					text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						store.reload();
					}
				});
			}
			return tbarOpr;
		},
		

		queryResItem : function(v) {
			var ptool = Ext.getCmp('page');
			if (!v) {
				v = ptool.pageSize;
			}
			store.load({
				params : {
					"start" : 0,
					"limit" : v
				}
			});

		},
		addInit : function() {
			this.onAddOrEditInit();
			win.show();
			win.setTitle('<div style="text-align:center;">新增车辆附件信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},

		
		editInit : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要修改的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条修改的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,false);
			win.show();
			win.setTitle('<div style="text-align:center;">修改车辆附件信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},
		show : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要查看的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条查看的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,true);
			win.show();
			win.setTitle('<div style="text-align:center;">查看车辆附件信息</div>');
			Ext.getCmp('btnSave').setVisible(false);
		},

		/**编辑或新增操作**/
		onAddOrEditInit : function(id,isShow) {
			if(!win){
				win = this.createWindow(id,isShow);
			} else {
				var temp_url;
				if(id!=undefined&& id!=''&& id!=null){
					temp_url=url+id;
				}else{
					temp_url=url;
				}
				if(isShow){
					temp_url+='&show=true';
				}
				document.getElementById("iframe").src=temp_url;
			}
		},
		/**查询附件信息**/
		attachView:function(file){
			if(!attachPanel){
				attachPanel=this.createAttachPanel();
			}
			if(!attachWin){
				attachWin = this.createAttachWindow();
			}
			$("#attachImg").attr('src',cfg.cxt+'/upload/'+file);
			$("#attachImg").show();
			attachWin.show();
		},
		/**创建附件panel**/
		createAttachPanel:function(){
			return new Ext.Panel({
	    		  layout : 'fit',
	    		  items: [{
			        	padding : 5,
						bodyStyle:'overflow-y:auto;overflow-x:hidden;',
						contentEl : 'attachImg'
			        }]
	    	  });
		},
		/**创建附件窗口**/
		createAttachWindow:function(){
			return new ExtWin({
    			width : 700,
  				height : 650,
  				title : '<div class="panelTitleCss">附件信息</div>',
    		  	items:[attachPanel],
    		  	buttons : [{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						$("#attachImg").hide();
						attachWin.hide();
					}
				}]
    		  });
		},
		subForm : function() {
			$('#subBtn', iframe.document).click();
		},

		tip : function(text) {
			Ext.Mytip.msg('提示', text);
		},

		closeWindow : function() {
			win.hide();
		},
		/**
		 * 显示窗口
		 */
		createWindow : function(id,isShow) {
			var frame_url;
			if(id!=undefined && id!=''&& id!=null){
				frame_url=url+id;
			}else{
				frame_url=url;
			}
			if(isShow){
				frame_url+='&show=true';
			}
			return new ExtWin({
			    width : 1024,
				height : 400,
				items : [{
					xtype : 'panel',
					html  : '<iframe id="iframe" src=' + frame_url+ ' scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>'
				}],
				buttons : [{
					text : '保存',
					id:"btnSave",
					iconCls : 'acceptIcon',
					handler : function() {
						iframe = document.getElementById("iframe").contentWindow;
						listView.subForm();
					}
				},{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						win.hide();
					}
				}]
			});
		},
		
		deleteItem : function() {
			var sm = grid.getSelectionModel();
			if (sm.getCount() == 0) {
				Ext.Mytip.msg('提示', '您尚未选择要删除的记记录！');
				return;
			}
			var ids = [];
			sm.each(function(r) {
				ids.push(r.data.id);
			});

			Ext.Msg.confirm('请确认',
					'<span style="color:red"><b>提示：</b>确定删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt + '/carAttach/del.action',
								success : function(response) {
									var rt = Ext.decode(response.responseText);
									if (rt.success) {
										// listView.queryResItem();
										store.reload();
										Ext.Mytip.msg('提示', '删除成功！');
									} else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"ids" : ids.join(',')
								}
							});
						}
					});
		}
	}
}();
Ext.onReady(listView.init, listView);
